import jieba
from wordcloud import WordCloud


def creat_word_cloud_image(str_file_path, stop_words=None, my_words=None):
    """
    创建词云图片
    :param str_file_path:
    :param stop_words:
    :param my_words:
    """
    # 文件夹路径
    if str_file_path.find('/') == -1:
        dir_path = ''
    else:
        dir_path = str_file_path[:str_file_path.rfind('/') + 1]

    filename = str_file_path[str_file_path.rfind('/') + 1:str_file_path.rfind('.')]
    cloud_path = dir_path + filename + '.png'

    # 读取词云文件
    text = open(str_file_path, encoding='utf-8').read()

    # font_path = 'simhei.ttf'
    font_path = 'C:\Windows\Fonts\STHUPO.ttf'  # 华文琥珀
    # font_path = 'C:\Windows\Fonts\STCAIYUN.ttf'# 华文彩云
    # font_path = 'C:\Windows\Fonts\STXINWEI.ttf'# 华文新魏

    wc = WordCloud(
        background_color='black',  # 设置背景颜色  默认是black
        width=800, height=600,
        max_words=10000,  # 词云显示的最大词语数量
        font_path=font_path,  # 设置字体  显示中文
        max_font_size=80,  # 设置字体最大值
        min_font_size=10,  # 设置字体最小值
        random_state=50,  # 设置随机生成状态，即多少种配色方案
        collocations=False
    )

    [jieba.add_word(word) for word in my_words]  # 添加自定义词
    [jieba.del_word(word) for word in stop_words]  # 删除停用词
    # 分词
    txt_list = jieba.lcut(text)
    # 过滤掉长度为1的词
    txt_list = list(filter(lambda x: len(x) > 1, txt_list))
    string = ",".join(txt_list)
    # 初始化词云
    wc.generate(string)
    wc.to_file(cloud_path)


if __name__ == '__main__':
    stop_words = ['詹姆斯']
    my_words = ['利拉德']
    creat_word_cloud_image('实战/文件/42961079.txt', stop_words=stop_words, my_words=my_words)
